# -*- coding: utf-8 -*-
import importlib
import os

IGNORE_DIRS = ['__pycache__']

MODULES = []
APPS = []


def load_application(application):
    if application in APPS:
        return
    from tank import app
    APPS.append(application)
    MODULES.append(importlib.import_module(application))
    try:
        middle = importlib.import_module('{}.middleware'.format(application))
        if hasattr(middle, 'before'):
            app.before_request(getattr(middle, 'before'))
        if hasattr(middle, 'after'):
            app.after_request(getattr(middle, 'after'))
    except ImportError as e:
        pass
    if app.debug:
        app.logger.debug("已加载应用: {}".format(application))


def load_applications(app):
    # 加载模块
    discover_package = app.config['DISCOVER_PACKAGE']
    apps_dir = importlib.import_module(discover_package).__path__[0]
    for application in os.listdir(apps_dir):
        if os.path.isdir(os.path.join(apps_dir, application)) and application not in IGNORE_DIRS:
            load_application("{}.{}".format(discover_package, application))


def depends(*dependencies):
    """
    :param dependencies: dependencies
    """
    for application in dependencies:
        load_application(application)
